package com.shujia.flink.source

import java.sql.{Connection, DriverManager, PreparedStatement, ResultSet}

import org.apache.flink.streaming.api.functions.source.SourceFunction

class Demo3MysqlSource extends SourceFunction[String] {

  override def run(ctx: SourceFunction.SourceContext[String]): Unit = {

    /**
      * 来纳杰mysql获取数据
      *
      */


    Class.forName("com.mysql.jdbc.Driver")


    val conn: Connection = DriverManager.getConnection("jdbc:mysql://master:3306/test", "root", "123456")

    val stat: PreparedStatement = conn.prepareStatement("select * from student")
    val resultSet: ResultSet = stat.executeQuery()

    while (resultSet.next()) {
      val id: String = resultSet.getString("id")
      val name: String = resultSet.getString("name")
      val age: Int = resultSet.getInt("age")
      val gender: String = resultSet.getString("gender")
      val clazz: String = resultSet.getString("clazz")


      val line: String = s"$id,$name,$age,$gender,$clazz"

      //将数据发送到下游
      ctx.collect(line)
    }

    conn.close()

  }

  override def cancel(): Unit = {

  }
}
